# -*- coding: utf-8 -*-
"""
Created on Mon Apr 19 20:53:23 2021

@author: 59567
"""
import sys
sys.path.append("../")
from tjdutils.utils import TjdDate, save_pickle, load_pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

class EasyForecast():
    
    def __init__(self, y_name, y_data, t, back_test_periods=5, data_type = "当月同比"):
        super(EasyForecast, self).__init__()
        self.y_name = y_name
        self.y_data = y_data
        self.b_t_p = back_test_periods # 回测期数
        self.data_type = data_type
        self.t = t
        self.mon_val = self.y_data['wind_当月值']
        self.mon_yoy = self.y_data['wind_当月同比']
        self.cum_val = self.y_data['wind_累计值']
        self.cum_yoy = self.y_data['wind_累计同比']
        self.mon_mom = self.y_data['wind_当月环比']        
        
    def predict(self):
        # 先把最近几年本月的当月值搞到手
        recent_year_mon_val = []
        for i in range(1, self.b_t_p):
            temp_t = self.t # 初始化开始时间
            for i_i in range(i):
                # 迭代创造历年本月
                temp_t = TjdDate(temp_t).dt['lymld']
            recent_year_mon_val.append(self.mon_val.loc[self.y_name, temp_t])
        yoy_li = []
        for i_n in range(1, self.b_t_p-1):
            yoy_li.append(recent_year_mon_val[i_n-1] / recent_year_mon_val[i_n] - 1)
        
        yoy_li = [d for d in yoy_li if d > 0]
        yoy_1 = np.average(yoy_li)

        last_year_t = TjdDate(self.t).dt['lymld']
        last_last_year_t = TjdDate(last_year_t).dt['lymld']
        # 上年累计
        last_year_cum_val = self.cum_val.loc[self.y_name, last_year_t]
        # 上月累计
        last_month_cum_val = self.cum_val.loc[self.y_name, TjdDate(self.t).dt['lmld']]
        # 上年当月值
        #last_year_mon_val = self.mon_val.loc[self.y_name, last_year_t]
        last_last_year_mon_val = self.mon_val.loc[self.y_name, last_last_year_t]
        # 本年本月当月值
        this_year_mon_val = (1 + yoy_1) * (1 + yoy_1) * last_last_year_mon_val
        # 本年本月累计值
        if pd.to_datetime(self.t).month == 1: # 如果一月当月值等于累计值
            this_month_cum_val = this_year_mon_val
        else: # 不是一月,累计值等于当月值+上月累计值
            this_month_cum_val = last_month_cum_val + this_year_mon_val
        #ttt = pd.to_datetime(self.t)
        #if ttt.month in [1, 2]:
            
        
        return this_month_cum_val / last_year_cum_val - 1

    def rolling_predict(self):
        all_predictions = {}
        for t in pd.date_range('2018-01-31', '2021-03-31', freq="M"):
            self.t = t
            all_predictions[t] = self.predict()
        return all_predictions

if __name__ == "__main__":
    y_data = load_pickle("D:/高频中台/2021_03_31/pipeline/gui/all_data_y.pkl")
    for name in ['房地产投资', '制造业投资', '基建投资']:
        east_forecast = EasyForecast(name, y_data, '2018-01-31')
        c = east_forecast.rolling_predict()
        a = y_data['wind_累计同比'].T.loc['2018-01-31':,name]
        a_f = pd.DataFrame(c, index=['s'])
        aa = a_f.T.iloc[:,0]
        # plt.plot(a)
        # plt.plot(aa)
        # plt.show()
        print(name, c)
